package com.xyzboom.web.servlets.resourse;

import com.xyzboom.utils.WebUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet(urlPatterns = "/resource", name = "ResourceHandlerServlet")
public class ResourceHandler extends HttpServlet {
    public static final String REQUEST_FROM_URL = "request_form_url";
    public static final String RESOURCE_TYPE_STR = "resource_type";
    public static final String RESOURCE_NAME_STR = "resource_name";
    public static final String RESOURCE_FROM_OTHER_STR = "other";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String other = request.getParameter(RESOURCE_FROM_OTHER_STR);
        String type = request.getParameter(RESOURCE_TYPE_STR);
        if (other != null) {
            WebUtils.forward(other, request, response);
            return;
        }
        if (type != null) {
            String name = request.getParameter(RESOURCE_NAME_STR);
            String path = request.getParameter(REQUEST_FROM_URL);
            if (path == null) return;
            WebUtils.forward(path.replace("pages", type) + "/" + name, request, response);
        }
    }

    public static final String RESOURCE_PATH_HEADER = "resource?";
    public static final String URL_AND = "&";
    public static final String URL_EQUAL = "=";

    public static String getResourcePath(String type, String name, HttpServletRequest request) {
        String result = request.getContextPath() + "/" +
                RESOURCE_PATH_HEADER +
                REQUEST_FROM_URL +
                URL_EQUAL +
                request.getServletPath().replace(".", "_") +
                URL_AND +
                RESOURCE_TYPE_STR +
                URL_EQUAL +
                type +
                URL_AND +
                RESOURCE_NAME_STR +
                URL_EQUAL +
                name;
        if (!name.endsWith("." + type)) {
            result += "." + type;
        }
        return result;
    }
}
